<!--
 * @Description: 用户留言
 * @Author: Kerwin
 * @Date: 2025-04-27 17:30:11
 * @LastEditTime: 2025-05-30 12:01:39
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="bigbox">
    <view style="text-align: right; margin-bottom: 20rpx">
      <u-button size="mini" type="warning" @click="handleGoHistory"
        >查看历史留言</u-button
      >
    </view>
    <view class="bigbox-t">
      <view class="bt">进行留言</view>
      <view style="margin-bottom: 50rpx">
        <van-field
          v-model="message"
          label="留言"
          type="textarea"
          placeholder="请输入留言"
          :autosize="{ maxHeight: 500, minHeight: 300 }"
          :show-confirm-bar="false"
          size="large"
          required
          clearable
        />
      </view>
    </view>
    <view class="bigbox-b">
      <view style="margin-bottom: 20rpx">
        <text style="font-weight: bold; font-size: 30rpx">上传图片</text>
        <text>（最多3张，选填）</text>
      </view>

      <view class="tpbox">
        <upImage
          ref="uploadRef"
          :showUploadList="true"
          name="object"
          :action="uploadUrl"
          :header="header"
          max-count="3"
          :multiple="false"
          :custom-btn="false"
          @on-success="handleUploadSuccess"
          @on-remove="handleRemove"
          @on-error="handleError"
          @on-change="handleChange"
          index="leavemessage"
          :file-list="showImageArr"
        >
        </upImage>
      </view>
      <view><u-button type="primary" @click="handleSure">确定</u-button></view>
    </view>
  </view>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { baseApi } from '@/api'
import { UPLOADURL } from '@/common/config'
import { getImgFullPath, getDistance } from '@/utils/index'
import { browserVersion, getCookie } from '@/utils/common'
import customUpload from '@/packageB/components/custom-upload/custom-upload.vue'
import upImage from '@/packageA/components/upImage/upImage.vue'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import { url } from 'inspector'
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
// 上传相关
const uploadRef = ref(null)
// 显示的图片列表，数组元素为对象，必须提供url属性
const showImageArr = ref<Array<{ url: string }>>([])
// 用于提交的图片数据
const tpArr = ref<any>([])
const uploadUrl = ref('https://api.yupengt.cn/base/api/v1/ali/sendFile')
const header = reactive({
  Authorization: `Bearer ${
    uni.getStorageSync('accessToken') || getCookie('HYToken') || ''
  }`
})
const message = ref('')
// 模式类型
const modelType = ref<any>(uni.getStorageSync('selfServiceModelType'))

onShow(() => {})
// 点击查看历史留言
const handleGoHistory = () => {
  uni.navigateTo({ url: `/packageA/pages/leaveMessage/messageList` })
}
// 图片上传成功
const handleUploadSuccess = (
  data: any,
  index: number,
  lists: any,
  name: any
) => {
  console.log('上传成功:', data, lists)
  if (data) {
    uni.showToast({
      title: '上传成功',
      icon: 'success'
    })
    tpArr.value = lists.map((ele: any) => ({
      resourceUrl: ele.response.data
    }))
  } else {
    uni.showToast({
      title: '上传失败',
      icon: 'error'
    })
  }
}
// 删除图片
const handleRemove = (index: number, lists: any, name: any) => {
  tpArr.value.splice(index, 1)
}
const handleError = (res: any, index: any, lists: any, name: any) => {
  console.log('上传失败res', res)
}
const handleChange = (res: any, index: any, lists: any, name: any) => {
  console.log('无论成功或者失败都会触发', res)
}

// 提交留言
const handleSure = async () => {
  // console.log('tpArr', tpArr.value)
  if (!message.value.trim()) {
    uni.showToast({
      title: '请输入留言内容',
      icon: 'none'
    })
    return
  }
  const { id, nickname, phone } = userInfo.value
  const tempobj = {
    userId: id,
    name: nickname,
    phone,
    remark: message.value,
    resources: tpArr.value.length > 0 ? tpArr.value : [],
    integralsRuleId: modelType.value
  }
  try {
    const res = await baseApi.addUserLeaveMessage({
      ...tempobj
    })
    // console.log('res', res)
    if (res.code === 200) {
      uni.showToast({
        title: '留言成功',
        icon: 'none'
      })
      handleClear()
      uni.navigateTo({ url: '/packageA/pages/selfService/index' })
    } else {
      uni.showToast({
        title: '留言失败',
        icon: 'none'
      })
    }
  } catch (error: any) {
    uni.showToast({
      title: error.message || '提交失败，请重试',
      icon: 'none'
    })
  }
}
// 清空数据
const handleClear = () => {
  message.value = ''
  showImageArr.value = []
  tpArr.value = []
}
</script>
<style lang="scss" scoped>
.bigbox {
  padding: 20rpx;
  .bigbox-t {
  }
  .bigbox-b {
    .tpbox {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #fff;
      padding-left: 25rpx;
      height: 300rpx;
      margin-bottom: 50rpx;
    }
  }
  .bt {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
}
</style>
